<template>
    <view class="page over-auto-y column">
        <!-- 头部 -->
        <hj-navbar title=" " :isShowBack="false" bgColor="#fff" v-if="!isInitLoad">
            <template #center>
                <hj-image src="logo-04.png" :isLoad="false" height="44rpx" mode="heightFix" />
            </template>
        </hj-navbar>
        <!-- 内容区 -->
        <view class="flex-auto w100 main over-hide" v-if="!isInitLoad">
            <scroll-view
                :scroll-y="true"
                class="big"
                :refresher-enabled="true"
                :refresher-triggered="triggered"
                @refresherrefresh="onRefresh"
            >
                <view class="pr-30 pl-30">
                    <!-- banner -->
                    <Banner :list="imageList" :total="imageTotal" />
                    <!-- 信息选择 -->
                    <InfoSelect @openDate="openDate" @openInfo="showCheckInInfo = true" />
                    <!-- 平台活动 -->
                    <Activity :list="msgList" v-if="msgList.length > 0" />
                    <!-- 推荐房型 -->
                    <RecomRoom :list="roomList" />
                </view>
            </scroll-view>
            <!-- 日历弹窗 -->
            <up-calendar-hj
                :show="show"
                :defaultDate="defaultDate"
                :monthNum="hotelInfo.calendarMonth"
                @close="show = false"
                @confirm="confirmDate"
            ></up-calendar-hj>
            <!-- 数量选择弹窗 -->
            <hj-checkIn-info
                :show="showCheckInInfo"
                @close="showCheckInInfo = false"
                @confirm="getRecomList"
            />
        </view>
        <!-- 底部tab、底部导航 -->
        <hj-footer-tabs :selectId="1" v-if="!isInitLoad" />
        <hj-loading :show="isInitLoad" v-if="isInitLoad" />
    </view>
</template>

<script setup>
/**
 * @description 小程序的首页
 * @author yinzhi
 * @date 2025-05
 */
import { onLoad, onShareAppMessage, onShareTimeline, onShow } from '@dcloudio/uni-app'
import { ref, defineComponent, watch, computed } from 'vue'
import { logger } from '@/utils/log.js'
import Banner from './components/Banner.vue'
import InfoSelect from './components/InfoSelect.vue'
import Activity from './components/Activity.vue'
import RecomRoom from './components/RecomRoom.vue'
import { getDefaultHotelBaseInfo, getHomeMsgApi, getImageListApi } from '@/libs/api/baseApi.js'
import { getRoomListApi } from '@/libs/api/roomApi.js'
// 引入组件
defineComponent({
    components: {
        Banner,
        InfoSelect,
        Activity,
        RecomRoom
    }
})
import { useStore } from 'vuex'
const store = useStore()
const isInitLoad = ref(true)
// 酒店ID 后续需要增加一个监听，当hotelId有值或者说发生变化时需要请求接口获取酒店信息并更新本地数据
const hotelId = ref('')
/**
 * @description 用户可能通过扫码或者分享过来的，需要在这里记住酒店id
 * @param {Object} e 扫码携带过来的参数或者分享过来的参数
 */
onLoad(async e => {
    if (e.scene) {
        const queryArray = await decodeURIComponent(e.scene)?.split('&')
        let queryObject = {}
        queryArray.forEach(async item => {
            var keyValue = item.split('=')
            var key = await decodeURIComponent(keyValue[0])
            var value = await decodeURIComponent(keyValue[1] || '')
            queryObject[key] = value
            if (key === 'hotelId') {
                hotelId.value = value
            }
        })
    }
    if (e.hotelId) {
        hotelId.value = e.hotelId
        await getHotelInfo(hotelId.value)
    }
	// 防止接口报错，导致页面长时间处在加载页面
	let times = setTimeout(()=>{
		isInitLoad.value = false;
		clearTimeout(times)
	},5000)
})
onShow(async () => {
    await store.dispatch('platform/initCheckInInfo')
})

// 下拉刷新控制参数
const triggered = ref(false)
const _freshing = ref(false)
// 日历弹窗
const show = ref(false)
// 数量选择弹窗
const showCheckInInfo = ref(false)
// 入住信息
const checkInInfo = computed(() => store.state.platform.checkInInfo || '')
// 默认时间区间
const defaultDate = computed(() => {
    return [checkInInfo.value.startDate, checkInInfo.value.endDate]
})
// 酒店信息
const hotelInfo = computed(() => store.state.platform.hotelInfo || '')

// 获取酒店信息
const getHotelInfo = async id => {
    try {
        const data = await getDefaultHotelBaseInfo({ id: id })
        const calendarMonth = data?.calendarMonth || 12
        store.commit('platform/setHotelInfo', {
            ...data,
            calendarMonth: calendarMonth + 1
        })
    } catch (error) {
        logger.error('[getRecomList] 首页获取酒店信息失败: ', error)
    }
}

// 打开日期选择弹窗
const openDate = async () => {
    try {
        await store.dispatch('platform/initHotelInfo')
        show.value = true
    } catch (error) {
        show.value = true
        logger.error('[getRecomList] 首页获取酒店信息失败: ', error)
    }
}

// 精选图片
const imageList = ref([])
const imageTotal = ref(0)

// 获取推荐图片列表
const getImageList = async () => {
    if (!hotelInfo.value.id) return
    try {
        const data = await getImageListApi({ categoryId: '', hotelId: hotelInfo.value?.id || '' })
        const selectedItem = data.find(item => item.name === '精选图片')
        imageList.value = selectedItem?.imageList?.slice(0, 8) || []
        imageTotal.value = data.reduce((total, item) => total + item.num, 0)
    } catch (error) {
        logger.error('[getImageListApi] 首页获取推荐图片列表失败: ', error)
    }
}

// 房型列表
const roomList = ref([])
// 获取推荐房型列表
const getRecomList = async () => {
    if (!checkInInfo.value?.startDate || !checkInInfo.value?.endDate) return
    try {
        const data = await getRoomListApi({
            checkInDate: checkInInfo.value.startDate || '',
            checkOutDate: checkInInfo.value.endDate || '',
            isHot: true,
            roomNum: checkInInfo.value.roomAmount,
            adultNum: checkInInfo.value.adult,
            childNum: checkInInfo.value.confirmhildren,
            hotelId: hotelInfo.value?.id || ''
        })
        roomList.value = data || []
    } catch (error) {
        logger.error('[getRecomList] 首页获取推荐房型列表失败: ', error)
    }
}

// 消息列表
const msgList = ref([])
// 获取消息通知
const getHomeMsg = async () => {
    if (!hotelInfo.value.id) return
    try {
        const data = await getHomeMsgApi({ id: hotelInfo.value.id })
        msgList.value = data || []
    } catch (error) {
        logger.error('[getHomeMsgApi] 首页获取消息通知失败: ', error)
    }
}

// 日历确认
const confirmDate = async e => {
    show.value = false
    await store.commit('platform/setCheckInInfo', {
        ...checkInInfo.value,
        startDate: e.date[0],
        endDate: e.date[e.date.length - 1],
        nightsCount: e.nightsCount
    })
    await getRecomList()
}

// 下拉刷新
const onRefresh = async () => {
    // 防止多次刷新
    if (_freshing.value) return
    _freshing.value = true
    triggered.value = true
    let time = setTimeout(() => {
        getRefresh()
        clearTimeout(time)
    }, 600)
}
// 刷新事件 等所有接口请求 完成后使刷新动画回弹
const getRefresh = () => {
    Promise.all([getRecomList(), getHomeMsg(), getImageList()])
        .then(() => {
            triggered.value = false
            _freshing.value = false
            isInitLoad.value = false
        })
        .catch(() => {
            triggered.value = false
            _freshing.value = false
            isInitLoad.value = false
        })
}

// 监听酒店id变化，请求接口获取酒店信息
watch(
    () => hotelInfo.value.id,
    async newValue => {
        if (newValue) {
            await getRefresh()
        }
    },
    { immediate: true }
)

// 点击小程序右上角分享
onShareAppMessage(() => {
    return {
        title: '懿家酒店邀您入住，快来看看吧！',
        path: `/pages/index/index?hotelId=${hotelInfo.value?.id || ''}`
    }
})

// 分享到朋友圈,只能分享当前页面，不能指定页面。
onShareTimeline(() => {
    return {
        title: '懿家酒店邀您入住，快来看看吧！',
        query: `hotelId=${hotelInfo.value?.id || ''}`
    }
})
</script>

<style scoped lang="scss">
.page {
    background: #fff;
    .main {
        background-color: #e0e1de; /* 兜底纯色（取渐变终点色）c8d3da */
        background-image: -webkit-linear-gradient(top, #ffd595, #e0e1de);
        background-image: linear-gradient(to bottom, #ffd595, #e0e1de);
        background-repeat: no-repeat;
        background-size: 100% 100%; /* 确保渐变铺满容器 */
    }
}
</style>
